<template>
  <el-popover placement="bottom"
              width="350"
              trigger="click">
    <el-tabs v-model="activeName" @tab-click="showList(null)">
      <el-tab-pane :label="'消息' + ((data.message.hintCount>0)?('(' + data.message.hintCount + ')'):'')"
                   name="message"></el-tab-pane>
      <el-tab-pane :label="'通知' + ((data.notice.hintCount>0)?('(' + data.notice.hintCount + ')'):'')"
                   name="notice"></el-tab-pane>
    </el-tabs>
    <el-scrollbar noticestyle style="height:300px">
      <el-row v-for="(item,idx) in data[activeName].list" style="width:340px;" :key="idx"
              :title="getFinalTooltipText(item,48)">
        <el-col :span="4" style="margin-bottom: 0px;">
          <div style="text-align: center;">
            <img :src="item.img" style="width: 24px;height:24px;">
          </div>
        </el-col>
        <el-col :span="10" style="margin-bottom: 0px;">
          <div style="text-align: left;">{{ item.subtitle }}</div>
        </el-col>
        <el-col :span="8" style="margin-bottom: 0px;">
          <div style="text-align: right;" @click="handleItemClick(item)">
            <el-button size="mini" :type="isClickEnable(item)?'primary':''" plain :disabled="!isClickEnable(item)"
                       style="padding: 4px 15px;">{{ item.tag }}
            </el-button>
          </div>
        </el-col>
        <el-col :offset="4" :span="18" style="margin-bottom: 0px;">
          <span v-if="!hasLink(item)">
            <div v-html="getTitleText(item)"></div>
          </span>
          <span v-else>
            <div v-html="getBeforeLinkText(item)"></div>
            <div v-if="isOpenWindow(item)">
              <a href="javascript:void(0)" @click="openOcPage(item)">{{getLinkText(item)}}</a>
            </div>
            <div v-else>
              <a href="javascript:void(0)" @click="openLocalPath(item)">{{getLinkText(item)}}</a>
            </div>
            <div v-html="getAfterLinkText(item)"></div>
          </span>
        </el-col>
        <el-col :offset="2" :span="20" style="margin-bottom: 0px;">
          <el-divider></el-divider>
        </el-col>
      </el-row>
      <el-row style="width:340px;">
        <el-col :span="24" style="margin-bottom: 0px;">
          <div style="text-align: center;" @click="pageChange(1,null)">
            <el-link>{{ getActionText() }}</el-link>
          </div>
        </el-col>
      </el-row>
    </el-scrollbar>
    <div slot="reference" class="beetles-ball">
      <el-badge :value="dotHint" type="warning">
        <i class="el-icon-bell"></i>
      </el-badge>
    </div>
    <div newPageLink></div>
  </el-popover>
</template>

<script>
import {getMessageHintList, setMessageRead} from "@/api/business/message";
import {getReleaseList as getNoticeList} from "@/api/desk/notice";
import {OC_LOGIN_URL} from "@/const/urlConst"
import {getToken} from '@/util/auth';
import {genTokenKey} from '@/api/user';
import website from "@/config/website";
import {createWebSocket} from "@/util/ws";
import { getEventMgr } from "@/util/events";
import {mapGetters} from "vuex";

export default {
  name: "top-notice",
  data() {
    return {
      activeName: 'message',
      offerId: null,
      dotHint: 0,
      activeNameList: ['message', 'notice'],
      option: {
        props: {
          img: 'img',
          title: 'title',
          subtitle: 'subtitle',
          tag: 'tag',
          status: 'status'
        },
      },
      data: {
        pageSize: 10,
        message: {
          hintCount: 0,
          unreadCount: 0,
          currentPage: 1,
          totalCount: 0,
          list: null
        },
        notice: {
          hintCount: 0,
          unreadCount: 0,
          currentPage: 1,
          totalCount: 0,
          list: null
        },
      },
    }
  },
  computed: {
    ...mapGetters(["userInfo", "token", "offer", "oc"]),
  },
  watch: {
    offer: {
      deep: true,
      handler(val, old) {
        if (val == null || val === old) {
          return
        }
        if(this.oc && this.offer != null && this.offer != '') {
          this.offerId = this.offer;
          this.refreshList('message');
        }
      }
    }
  },
  created() {
    if(this.oc && this.offer != null && this.offer != '') {
      this.offerId = this.offer;
    }
  },
  mounted() {
    let self = this;
    self.refreshList();
    if (!self.socket) {
      self.socket = createWebSocket('/api/blade-system/wss', 'json');
      if (self.socket) self.socket.ontextmessage = (msg) => {
        let msgObj = JSON.parse(msg);
        //console.log("socket receive:" + msg)
        if (msgObj) {
          if (msgObj.messageName === 'userMessage' && msgObj.data.messageName == 'messageRefresh') {
            if(msgObj.data.offerId == null || self.offerId == null || msgObj.data.offerId == self.offerId) {
              self.refreshList('message');
            }
          }
          if (msgObj.messageName === 'tenantMessage' && msgObj.data.messageName == 'noticeRefresh') {
            self.refreshList('notice');
          }
        }
      };
      if (self.socket) self.socket.onerror = () => {
        this.$message({
          type: 'warning',
          message: '您的网络目前不稳定，数据可能不能自动刷新！'
        });
      };
    }
  },
  beforeDestroy() {
    let self = this;
    if (self.socket) {
      self.socket.close();
      self.socket = null;
    }
  },
  methods: {
    getActionText() {
      let self = this;
      return (self.data[self.activeName].list != null && self.data[self.activeName].list.length < self.data[self.activeName].totalCount) ? "加载更多" : "刷新数据";
    },
    getTooltipText(s, l) {
      //s = s.replace(/['"]/ig,"");
      let byteCount = 0;
      for (let p = 0; p < s.length; p++) {
        if (s.charCodeAt(p) > 128) {
          if ((byteCount + 2) > l) {
            return s.substring(0, p) + '\n' + this.getTooltipText(s.substring(p), l);
          }
          byteCount += 2;
        } else {
          if ((byteCount + 1) > l) {
            return s.substring(0, p) + '\n' + this.getTooltipText(s.substring(p), l);
          }
          byteCount++;
        }
      }
      return s;
    },
    updateDotHint() {
      let self = this;
      let hintCount = 0;
      for (let i = 0; i < self.activeNameList.length; i++) {
        hintCount += self.getHintCount(self.activeNameList[i]);
      }
      self.dotHint = hintCount;
    },
    getCurrentPage(dataLength, pageSize) {
      let currentPage = Math.floor((dataLength + pageSize - 1) / pageSize);
      if (currentPage == 0) currentPage = 1;
      return currentPage;
    },
    refreshList(name) {
      if (!this.token)
        return;
      let self = this;
      for (let i = 0; i < self.activeNameList.length; i++) {
        let activeName = self.activeNameList[i];
        if (name) {
          if (activeName != name) {
            continue;
          }
        }
        let newPageSize = self.data.pageSize * self.data[activeName].currentPage;
        self.loadList(activeName, 1, newPageSize, (myres) => {
          self.data[activeName].list = myres.list;
          self.data[activeName].totalCount = myres.totalCount;
          self.data[activeName].currentPage = self.getCurrentPage(myres.list.length, self.data.pageSize);
          self.data[activeName].unreadCount = myres.unreadCount;
          self.data[activeName].hintCount = self.getHintCount(activeName);
          self.updateDotHint();
        });
      }
      // setTimeout(() => {
      //     self.refreshList();
      // },60000);
    },
    loadList(activeName, pageNo, pageSize, cbFunc) {
      let self = this;
      if (activeName == "message") {
        getMessageHintList(pageNo, pageSize, {
          userId: self.userInfo.user_id,
          tenantId: self.userInfo.tenant_id,
          offerId: self.offerId,
        }).then(res => {
          let mylist = [];
          let totalCount = 0;
          let unreadCount = 0;
          if (res.data.code === 200 && res.data.success == true) {
            let pageList = res.data.data.pageList;
            totalCount = pageList.total;
            unreadCount = res.data.data.unreadCount;
            for (let i = 0; i < pageList.records.length; i++) {
              if (pageList.records[i].readFlag == 0) {
                mylist[mylist.length] = {
                  img: '/img/bg/vip3.png',
                  title: pageList.records[i].messageText,
                  subtitle: pageList.records[i].createTime,
                  status: 0,
                  tag: '未读',
                  id: pageList.records[i].id,
                  href: (pageList.records[i].href == null || pageList.records[i].href == '')?null:JSON.parse(pageList.records[i].href),
                };
              } else {
                mylist[mylist.length] = {
                  img: '/img/bg/vip4.png',
                  title: pageList.records[i].messageText,
                  subtitle: pageList.records[i].createTime,
                  status: 1,
                  tag: '已读',
                  id: pageList.records[i].id,
                  href: (pageList.records[i].href == null || pageList.records[i].href == '')?null:JSON.parse(pageList.records[i].href),
                };
              }
            }
          }
          cbFunc({currentPage: pageNo, totalCount: totalCount, list: mylist, unreadCount: unreadCount});
        });
      } else if (activeName == 'notice') {
        getNoticeList(pageNo, pageSize, {}).then(res => {
          let mylist = [];
          let totalCount = 0;
          if (res.data.code === 200 && res.data.success == true) {
            totalCount = res.data.data.total;
            for (let i = 0; i < res.data.data.records.length; i++) {
              mylist[mylist.length] = {
                img: '/img/bg/vip3.png',
                title: res.data.data.records[i].content,
                subtitle: res.data.data.records[i].releaseTime,
                status: res.data.data.records[i].status,
                tag: res.data.data.records[i].categoryName,
                id: res.data.data.records[i].id
              };
            }
          }
          cbFunc({currentPage: pageNo, totalCount: totalCount, list: mylist, unreadCount: 0});
        });
      }
    },
    isClickEnable(item) {
      let self = this;
      let activeName = self.activeName;
      if (activeName == 'message') {
        return (item.status === 0);
      }
      return false;
    },
    handleItemClick(item) {
      let self = this;
      let activeName = self.activeName;
      if (activeName == 'message') {
        if (item.status === 0) {
          let oldUnreadCount = self.data[activeName].unreadCount;
          setMessageRead(item.id).then(res => {
            if (res.data.code === 200 && res.data.success === true) {
              //消息通知走的是websocket通道，有些情况会快于操作返回
              if(oldUnreadCount == self.data[activeName].unreadCount) {
                self.data[activeName].unreadCount--;
                item.status = 1;
                item.tag = '已读';
                item.img = '/img/bg/vip4.png';
                self.data[activeName].hintCount = self.getHintCount(activeName);
                self.data[activeName].list.sort((a, b) => {
                  if (a.status > b.status) return 1;
                  if (a.status < b.status) return -1;

                  if (a.subtitle > b.subtitle) return -1;
                  if (a.subtitle < b.subtitle) return 1;   //时间越新越在前

                  return 0;
                });
                self.updateDotHint();
              }
            }
          });
        }
      }
    },
    showList(actName) {
      let self = this;
      let activeName = actName || self.activeName;
      if (self.data[activeName].list == null) {
        self.loadList(activeName, 1, self.data.pageSize, (mylist) => {
          self.data[activeName].list = mylist.list;
          self.data[activeName].currentPage = mylist.currentPage;
          self.data[activeName].totalCount = mylist.totalCount;
          self.data[activeName].unreadCount = mylist.unreadCount;
          self.data[activeName].hintCount = self.getHintCount(activeName);
          self.updateDotHint();
        });
      }
    },
    getHintCount(activeName) {
      let self = this;
      let hintCount = 0;
      if (activeName == "message") {
        hintCount = self.data[activeName].unreadCount;
      }
      if (activeName == "notice") {
        hintCount = self.data[activeName].totalCount;
      }
      return hintCount;
    },
    /**
     * 如果当前页记录不足页，则刷新所有记录，否则追加新页
     * 当前页重新计算
     */
    pageChange(page, done) {
      let self = this;
      let activeName = self.activeName;
      setTimeout(() => {
        let nextPage = 1;
        let nextPageSize = self.data.pageSize;
        if (self.data[activeName].totalCount > 0 && self.data[activeName].list != null) {
          let currPage = self.getCurrentPage(self.data[activeName].list.length, self.data.pageSize);
          if ((currPage * self.data.pageSize) == self.data[activeName].list.length) {
            if (self.data[activeName].totalCount > self.data[activeName].list.length) {
              nextPage = currPage + 1;
            } else {
              nextPage = 1;
              nextPageSize = currPage * self.data.pageSize;
            }
          } else {
            nextPage = 1;
            nextPageSize = currPage * self.data.pageSize;
          }
        }
        //self.$message.success('页码' + nextPage);
        self.loadList(activeName, nextPage, nextPageSize, (myres) => {
          if (self.data[activeName].list == null || nextPage == 1) {
            self.data[activeName].list = [];
          }
          self.data[activeName].list = self.data[activeName].list.concat(myres.list);
          self.data[activeName].currentPage = self.getCurrentPage(self.data[activeName].list.length, self.data.pageSize);
          self.data[activeName].totalCount = myres.totalCount;
          self.data[activeName].unreadCount = myres.unreadCount;
          self.data[activeName].hintCount = self.getHintCount(activeName);
          self.updateDotHint();
        });
        if (done) {
          done();
        }
      }, 200)

    },

    getTokenKeyInfo(item) {
      if(item.href.target == 'creativeRequest') {
        return JSON.stringify({offerId: item.href.data.offerId,r: '/creativerequest'});
      }
      if(item.href.target == 'editCreativeRequest') {
        return JSON.stringify({offerId: item.href.data.offerId,r: '/creativerequest',ropList: [{rid: item.href.data.creativeRequestId,rop: 'editCreativeRequest'}]});
      }
      if(item.href.target == 'creativeDetail') {
        return JSON.stringify({offerId: item.href.data.offerId,r: '/creative',ropList: [{rid: item.href.data.creativeId,rop: 'creativeDetail'}]});
      }
      return '';
    },
    openOcPage(item) {
      let ocTokenKey = '';
      let headers = {};
      headers[website.tokenHeader] = getToken();
      genTokenKey({
        sync: true,
        headers: headers,
        info: this.getTokenKeyInfo(item),
        success: (data) => {
          ocTokenKey = data.tokenKey;
        },
        error: () => {
        }
      });
      if(ocTokenKey == '') {
        this.$message.error('获取信息错误，无法正确跳转到订单中心');
        return;
      }
      let eleList = document.querySelectorAll('div[newPageLink]');
      let content = eleList[0];
      let linkEle = document.createElement("a");
      content.appendChild(linkEle);

      // 利用URL.createObjectURL()方法为a元素生成blob URL
      linkEle.target = '_blank';
      linkEle.href = OC_LOGIN_URL + '?tokenKey=' + ocTokenKey;
      linkEle.click();
      linkEle.remove();
    },
    toHtmlText(s) {
      if(s == null) {
        return null;
      }
      return s.trim().replaceAll('\n','<br>');
    },
    getFinalTooltipText(item,l) {
      if(this.activeName == 'message') {
        if(item.href != null) {
          return this.getTooltipText(item.title.replaceAll('$HREF$',item.href.text),l);
        } else {
          return this.getTooltipText(item.title,l);
        }
      } else {
        return this.getTooltipText(item.title,l);
      }
    },
    getTitleText(item) {
      if(this.activeName == 'message') {
        return this.toHtmlText(item.title);
      } else {
        return item.title;
      }
    },
    getLinkText(item) {
      return item.href.text;
    },
    getBeforeLinkText(item) {
      return this.toHtmlText(item.title.substring(0,item.title.indexOf('$HREF$')));
    },
    getAfterLinkText(item) {
      return this.toHtmlText(item.title.substring(item.title.indexOf('$HREF$') + '$HREF$'.length));
    },
    openLocalPath(item) {
      let self = this;
      let pageInfo = null;
      let targetList = ['creativeRequest','editCreativeRequest','creativeDetail'];
      if(targetList.includes(item.href.target)) {
        let sPageInfo = this.getTokenKeyInfo(item);
        if(sPageInfo != '') {
          pageInfo = JSON.parse(sPageInfo);
        }
      }
      if(pageInfo == null) {
        return;
      }
      self.$store.commit('SET_OFFER',pageInfo.offerId);
      window.sessionStorage.setItem("initPageInfo", JSON.stringify(pageInfo));
      if(pageInfo.ropList != null) {
        getEventMgr('offerCenter').sendEvent({message: 'initPage', offerId: this.offerId});
      }
      self.$router.push({path:pageInfo.r});
    },

    hasLink(item) {
      let self = this;
      let activeName = self.activeName;
      if (activeName == 'message') {
        if(item.title.indexOf('$HREF$') >= 0 && item.href != null) {
          return true;
        }
      }
      return false;
    },
    isOpenWindow(item) {
      if(!this.oc) {
        let ocTarget = ['creativeRequest','editCreativeRequest','creativeDetail'];
        if(ocTarget.includes(item.href.target)) {
          return true;
        }
      }
      return false;
    },
  }
};
</script>
<style lang="scss">
/deep/ .text_ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 200px;
}
.beetles-ball {
  >.el-badge{
    >.is-fixed {
      top: 1.5em !important;
      right: 0.6em !important;
    }
  }
}
//.top-bar__item .el-badge__content.is-fixed {
//  top: 1.5em;
//  right: 0.6em;
//}
</style>
<style lang="scss" scoped>
  /deep/a {
    color: rgb(0, 162, 255);
  }
</style>
